package com.mi.million.common.service.file;

import com.alibaba.fastjson.JSON;
import com.mi.million.common.util.FileKit;
import com.mi.million.common.util.SystemKit;
import com.mi.million.common.util.ValidateKit;
import com.mi.million.module.system.service.DictService;
import com.mi.million.mybatis.entity.FileInfo;
import com.mi.rule.db.dao.MiDao;
import com.mi.rule.util.EnvKit;
import com.mi.rule.util.project.MiException;
import com.mi.rule.util.project.SRS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;

@Slf4j
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MiDao dao;
    @Autowired
    private DictService dictService;

    @Override
    public SRS upload(MultipartFile[] files) throws Exception {
        if (files == null || files.length == 0) {
            return SRS.bySuccess();
        }
        String uploadPath = uploadPath();

        //获取文件上传路径
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //      检查文件大小
        Long upload_file_max_size = dictService.getLong("upload_file_max_size");
        long maxSize = 0L;
        if (upload_file_max_size != null) maxSize = upload_file_max_size * (1024 * 1024);
        if (upload_file_max_size != null) {
            for (MultipartFile file : files) {
                if (file.getSize() > maxSize) {
                    throw new MiException("文件上传超出最大限制 " + upload_file_max_size + "M");
                }
            }
        }

        //    开始上传
        ArrayList<FileInfo> listUpload = new ArrayList<>();
        for (MultipartFile file : files) {
            //原始文件名（有后缀）
            String originalFilename = file.getOriginalFilename();
            //文件后缀（没有点）
            String suffix = FileKit.getSuffix(originalFilename);
            String fileMd5 = FileKit.getFileMd5(file); //文件 MD5
            String fileName = fileMd5 + "." + suffix;
            String type = getType(originalFilename);//文件类型
            String url = "/static/" + type + "/" + fileName;
            String serverUrl = EnvKit.getProperty("server.servlet.context-path");
            if (serverUrl != null) {
                url = serverUrl + url;
            }

            String path = (uploadPath + SystemKit.sp + type + SystemKit.sp);

            //上传文件
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path, fileName));

            //保存信息
            FileInfo fileInfo = new FileInfo();
            fileInfo.setName(originalFilename);
            fileInfo.setSize(file.getSize() + "");
            fileInfo.setType(type);
            fileInfo.setSuffix(suffix);
            fileInfo.setMd5(fileMd5);
            fileInfo.setUrl(dictService.getValue("upload_file_access_url") + url);
            listUpload.add(fileInfo);
        }

        //批量添加
        dao.insertBatch(listUpload);
        log.info("listUpload : {}", JSON.toJSONString(listUpload));
        return SRS.bySuccess(listUpload);
    }


    private String uploadPath() {
        if (SystemKit.isLinux()) {
            return dictService.getValue("upload_file_path_linux");
        }
        return dictService.getValue("upload_file_path_windows");
    }

    public static String getType(String originalFilename) {
//        JPG、JPEG、PNG、GIF
        if (ValidateKit.isImage(originalFilename)) {
            return "image";
        }
        if (ValidateKit.isVideo(originalFilename)) {
            return "video";
        }
        return "other";
    }

}
